package com.ubing.boot.notesforjava.test.NIO;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName : test_sync
 * @Description : test_sync
 * @Author : Xxxxx
 * @Date: 2023-03-16 15:41
 */
public class test_sync {
    int i=11;

    void geti(){
        System.out.println(i);
    }

    synchronized void changei(int i){
        System.out.println("加锁");
        this.i=i;
        try {
            TimeUnit.SECONDS.sleep(3);
            changei(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("锁释放");
    }

    public static void main(String[] args) throws InterruptedException {


        final Object o=new Object();

        final Object o1=new Object();

        Thread t1= new Thread(()->{
            synchronized (o){
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1拿到o");
                synchronized (o1){
                    System.out.println("线程1拿到o1");


             }
            }
        });

        Thread t2= new Thread(()->{
            synchronized (o1){
                System.out.println("线程2拿到o1");
                synchronized (o){
                    System.out.println("线程2拿到o");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();


    }
}
